//
//  HaokaViewController.m
//  BMProject
//
//  Created by chris on 16/1/2.
//  Copyright © 2016年 BMProject. All rights reserved.
//

#import "HaokaViewController.h"
#import "HaokaTopCell.h"
#import "HaokaMiddleHeaderView.h"
#import "HaokaMiddleCell.h"
#import "HaokaBottomCell.h"
#import "DataModel.h"
#import "NSObjectAdditions.h"
#import "SelectDeliveryMethyVc.h"
#import "DitchManageChangeVc.h"

@interface HaokaViewController () <UIAlertViewDelegate>{
    OrderDealDetailOrderInfo *_orderInfo;
    OrderDealDetailOrderContentInfo *_contentInfo;
    UITableView *_tableview;
    HaokaMiddleHeaderView *_middleHeaderView;
    NSMutableArray *_orderDealDetailPoolList;//OrderDealDetailPoolList 数据
    NSMutableArray *_telList;//TelList 数据
}
@end

@interface HaokaViewController () <UITableViewDataSource, UITableViewDelegate>

@end

@implementation HaokaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"工单信息确认";
    UITableView *tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    tableview.delegate = self;
    tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableview.sectionHeaderHeight = 8.0;
    tableview.sectionFooterHeight = 8.0;
    tableview.dataSource = self;
    tableview.allowsMultipleSelection = YES;
    _tableview = tableview;
    tableview.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 10)];
    [self addSubview:tableview];
    _orderDealDetailPoolList = [NSMutableArray array];
    _telList = [NSMutableArray array];

    [self inquireBtnAction:nil];
    [self requestDetail];
}

#pragma mark-UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0 || section == 2) {
        return 1;
    }
    else {
        if (_model.sign.intValue  == 0) {
            return _orderDealDetailPoolList.count;
        } else {
            return _telList.count;
        }
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *cellId = @"HaokaTopCell";
        HaokaTopCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:cellId owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.vc = self;
        [cell setInfo:_model];
        [cell setOrderContentInfo:_contentInfo];
        return cell;
    }
    else if (indexPath.section == 1) {
        static NSString *cellId = @"HaokaMiddleCell";
        HaokaMiddleCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:cellId owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell setIndexPath:indexPath];
        if (_model.sign.intValue == 0) {//确认状态
        } else{
            //todo 这里要隐藏search的view 还要更换号码数据源
            cell.isCancleImage = YES;
        }
        if (_model.sign.intValue  == 0) {
            if (indexPath.row < _orderDealDetailPoolList.count) {
                [cell setCellInfo:_orderDealDetailPoolList[indexPath.row]];
            } else {
                [cell setCellInfo:nil];
            }
        } else {
            if (indexPath.row < _telList.count) {
                [cell setCellInfo2:_telList[indexPath.row]];
            } else {
                [cell setCellInfo:nil];
            }
        }
        return cell;
    }
    else {
        static NSString *cellId = @"HaokaBottomCell";
        HaokaBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:cellId owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell setOrderContentInfo:_contentInfo];
        return cell;

    }

}

#pragma mark-UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 150;
    }
    else if (indexPath.section == 2) {
        return 90;
    }
    else
        return 30 * ratio_heigth;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        if (_model.sign.intValue == 0) {//确认状态
            return 80;
        } else{
            //todo 这里要隐藏search的view 还要更换号码数据源
            return 40;
        }
    }
    else
        return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 2) {
        return 50;
    }
    else
        return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        HaokaMiddleHeaderView *header = [[[NSBundle mainBundle] loadNibNamed:@"HaokaMiddleHeaderView" owner:self options:nil] lastObject];
        header.frame = CGRectMake(0, 0, DEF_SCREEN_WIDTH, 80);
        [header.InquireBtn addTarget:self action:@selector(inquireBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        header.clipsToBounds = YES;
        _middleHeaderView = header;
        return header;
    }
    return nil;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (_type == ORDER_LOOK_TYPE) {
        return nil;
    }
    if (section == 2) {
        UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 50)];
        footer.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1];
        UIButton *sureBtn = [UIButton buttonWithType:0];
        sureBtn.frame = CGRectMake(DEF_SCREEN_WIDTH / 2 - 50, 10, 100, 30);
        sureBtn.layer.cornerRadius = 5.0;
        sureBtn.layer.masksToBounds = YES;
        sureBtn.backgroundColor = [UIColor orangeColor];
        sureBtn.titleLabel.font = font(13);
        if (_model.sign.intValue == 0) {
            [sureBtn setTitle:@"确认" forState:UIControlStateNormal];
        } else if (_model.sign.intValue == 1) {
            [sureBtn setTitle:@"发货" forState:UIControlStateNormal];
        } else {
            [sureBtn setTitle:@"确认" forState:UIControlStateNormal];
        }
        [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [sureBtn addTarget:self action:@selector(sureBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [footer addSubview:sureBtn];

        return footer;
    }
    return nil;
}

- (void)requestDetail {
    //Type=2 类型为号卡工单时的返回报文
    if (_model.sign.intValue == 0) {//确认状态
        [UserServices orderAuditDetailByToen:[[AppDelegate appDelegate] getUserInfo].token
                                          id:_model.id
                                        sign:_model.sign
                                        type:_model.type
                                  showDialog:YES
                             completionBlock:^(int result, id responseObject) {
                                 if (result == API_Request_Success) {
                                     NSDictionary *responseDict = responseObject[0];
                                     NSDictionary *orderInfoDic = [responseDict objectForKey:@"orderInfo"];
                                     NSDictionary *orderContentInfoDic = [responseDict objectForKey:@"orderContentInfo"];
                                     NSMutableArray *poolList = [responseDict objectForKey:@"poolList"];//数组
                                     _orderInfo = [[OrderDealDetailOrderInfo alloc] initWithDictionary:orderInfoDic error:nil];
                                     _contentInfo = [[OrderDealDetailOrderContentInfo alloc] initWithDictionary:orderContentInfoDic error:nil];
                                     [_tableview reloadData];
                                 }
                             }];
    } else {
        [UserServices orderAuditFahuoByToen:[[AppDelegate appDelegate] getUserInfo].token
                                         id:_model.id
                                 showDialog:YES
                            completionBlock:^(int result, id responseObject) {
                                if (result != API_COULD_NOT_CONNECT_ERROR) {
                                    NSDictionary *responseDict = responseObject[0];
                                    NSDictionary *orderInfoDic = [responseDict objectForKey:@"orderInfo"];
                                    NSDictionary *orderContentInfoDic = [responseDict objectForKey:@"orderContentInfo"];
                                    NSMutableArray *telList = [responseDict objectForKey:@"telList"];//数组
                                    _orderInfo = [[OrderDealDetailOrderInfo alloc] initWithDictionary:orderInfoDic error:nil];
                                    _contentInfo = [[OrderDealDetailOrderContentInfo alloc] initWithDictionary:orderContentInfoDic error:nil];
                                    for (int i = 0; i < telList.count; ++i) {
                                        TelModel *telModel =  [[TelModel alloc] initWithDictionary:telList[i] error:nil];
                                        [_telList addObject:telModel];
                                    }
                                    [_tableview reloadData];
                                }
                            }];
    }
}

/**
 *
 */
- (void)sureBtnAction:(UIButton *)sureBtn {
    DLog(@"确认按钮...");
    if (_model.sign.intValue == 0) {//确认状态
        NSArray *selectedRows = [_tableview indexPathsForSelectedRows];//NSIndexPath
        if (!(selectedRows && selectedRows.count > 0)) {
            [SVProgressHUD showErrorWithStatus:@"没有可用的号段"];
            return;
        }
        NSString *mobileStr = @"";
        for (int j = 0; j < selectedRows.count; ++j) {
            NSIndexPath *indexPath = ((NSIndexPath *) selectedRows[j]);
            if (indexPath.section == 1) {
                DLog([NSString stringWithFormat:@"选中的行数:%i", indexPath.row]);
                OrderDealDetailPoolList *pool = _orderDealDetailPoolList[indexPath.row];
                NSString *mobile = pool.mobile;
                if (IsStringEmpty(mobileStr)) {
                    mobileStr = [mobile stringByAppendingString:mobileStr];
                } else {
                    mobileStr = [[mobile stringByAppendingString:@","] stringByAppendingString:mobileStr];
                }
            }
        }
        if (![NSString notEmptyOrNull:mobileStr]) {
            return;
        }
        [UserServices orderAuditConfirmHaoKaByToken:[[AppDelegate appDelegate] getUserInfo].token
                                             mobile:mobileStr
                                                 id:_contentInfo.id
                                            basicId:_model.id
                                         showDialog:YES completionBlock:^(int result, id responseObject) {
                    if (result == API_Request_Success) {
                        if (responseObject && [responseObject isKindOfClass:[NSArray class]]) {
                            //[{"flag":"0","msg":"提交成功！",” poolWarning”,”您的号池告不足30个”}]
                            NSDictionary *dictionary = responseObject[0];
                            int  flag = ((NSString *)(dictionary[@"flag"])).intValue;
                            NSString *poolWarning = dictionary[@"poolWarning"];
                            NSString *msg  = dictionary[@"msg"];
                            if (flag == 0) {
                                UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"提交成功"
                                                                 message:poolWarning
                                                                delegate:self
                                                       cancelButtonTitle:nil
                                                       otherButtonTitles:@"确定", nil];
                              [av show];
                            } else {
                                [SVProgressHUD showErrorWithStatus:msg];
                            }
                        }
                    }
                }];

    } else {
        [UserServices orderAuditOptByToken:[[AppDelegate appDelegate] getUserInfo].token
                                   basicId:_model.id
                                       opt:@"fahuo"
                               expressName:@""
                                expressNum:@""
                             expressRemark:@""
                                  sendType:@""
                                showDialog:YES
                           completionBlock:^(int result, id responseObject) {
                               SelectDeliveryMethyVc *selectDeliveryMethyVc = [[SelectDeliveryMethyVc alloc] init];
                               selectDeliveryMethyVc.model = _model;
                               [self.navigationController pushViewController:selectDeliveryMethyVc animated:YES];
                           }];

    }

}

/**
 * 号卡查询
 */
- (void)inquireBtnAction:(UIButton *)inquireBtn {
    DLog(@"号卡查询...");
    if (_model.sign.intValue != 0) {
        return;
    }
    [UserServices orderAuditGetPoolsByToken:[[AppDelegate appDelegate] getUserInfo].token
                                    segment:[NSString ignoreEmptyStr:_middleHeaderView.haoduanTF.text replaceStr:@"   "]
                                 showDialog:YES
                            completionBlock:^(int result, id responseObject) {
                                [_orderDealDetailPoolList removeAllObjects];
                                if (result == API_Request_Success && [responseObject isNSArray]) {
                                    [_orderDealDetailPoolList addObjectsFromArray:responseObject];
                                    if (inquireBtn != nil && _orderDealDetailPoolList.count == 0) {
                                        [SVProgressHUD showErrorWithStatus:@"查无数据!"];
                                    }
                                }
                                [_tableview reloadData];
                            }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
